package jsyf.oa.web.thurTrack;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jsyf.com.util.*;
import jsyf.oa.facade.system.MessageFacade;
import jsyf.oa.facade.thurTrack.ThurTrackFacade;
import jsyf.oa.web.socket.MyWebSocketHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Maqiuqiu on 2018/8/16.
 */
@Api(value = "每周三商机跟踪接口", description = "每周三商机跟踪接口")
@Controller
@RequestMapping("/thurTrack")
public class ThurTrackController {

    @Resource
    private ThurTrackFacade thurTrackFacade;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @RequestMapping(value = "/save.json", method = RequestMethod.POST)
    public void save(HttpServletResponse response, @RequestBody String jsonData) {
        String resultId = this.thurTrackFacade.save(jsonData);
        String result = "";
        if ("".equals(resultId)) {
            result = BaseUtils.errorrRespond("服务器错误");
        } else {
            JSONObject obj = new JSONObject();
            obj.put("id", resultId);
            result = BaseUtils.succsessObjTimeRespond(obj);
        }
        ResponseUtils.putJsonResponse(response, result);
    }

    @RequestMapping(value = "/allCommit.json", method = RequestMethod.POST)
    public void allCommit(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject resultIds = this.thurTrackFacade.allCommit(jsonData);
        String results = "";
        if ("".equals(resultIds)) {
            results = BaseUtils.errorrRespond("服务器错误");
        } else {
            JSONObject obj = new JSONObject();
            obj.put("ids", resultIds);
            //发送消息
            sendMessage(obj.getString("message"));
            obj.remove("message");
            results = BaseUtils.succsessObjTimeRespond(obj);
        }
        ResponseUtils.putJsonResponse(response, results);
    }

    @RequestMapping(value = "/allAdd.json", method = RequestMethod.POST)
    public void allAdd(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject resultIds = this.thurTrackFacade.allAdd(jsonData);
        String results = "";
        if ("".equals(resultIds)) {
            results = BaseUtils.errorrRespond("服务器错误");
        } else {
            JSONObject obj = new JSONObject();
            obj.put("ids", resultIds);
            results = BaseUtils.succsessObjTimeRespond(obj);
        }
        ResponseUtils.putJsonResponse(response, results);
    }

    @RequestMapping(value = "/getTrackById.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "根据id获取预测",
            notes = "根据id获取预测",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData",value = "{id:''}",dataType = "String", paramType = "body")
    public void getTrackById(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getTrackById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

    @RequestMapping(value = "/getTrackDetail.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "根据id获取预测",
            notes = "根据id获取预测",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData",value = "{id:''}",dataType = "String", paramType = "body")
    public void getTrackDetail(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getTrackDetail(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

    @RequestMapping(value = "/getThurTrackList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "分页获取预测",
            notes = "分页获取预测",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getThurTrackList(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getThurTrackList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

    @RequestMapping(value = "/applyAudit.json", method = RequestMethod.POST)
    public void applyAudit(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = thurTrackFacade.applyAudit(jsonData);
        boolean flag = Boolean.parseBoolean(result.getString("flag"));
        //发送消息
        sendMessage(result.getString("message"));
        if (flag) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond());
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("审核失败"));
        }
    }

    @RequestMapping(value = "/getDownByCondition.json", method = RequestMethod.GET)
    public void getDownByCondition(HttpServletRequest request, HttpServletResponse response, @RequestParam String userId,@RequestParam String companyId,@RequestParam String bigRegionalId,@RequestParam String regionalManagerId,@RequestParam String key,@RequestParam String fieldList,@RequestParam String date) throws Exception {
        //查出来的数据
        List<JSONObject> records = this.thurTrackFacade.getDownList(userId,companyId,bigRegionalId,regionalManagerId,key,date);
        for (int i = 0; i < records.size(); i++) {
            JSONObject jsonObject = records.get(i);
            String confirmationStatus = jsonObject.getString("confirmationStatus");
            if(confirmationStatus.equals("Machine delivered to customer已交车")){
                records.get(i).put("confirmationStatus", "Machine delivered to customer已放车");
            }
        }
        getDownExcel(records,fieldList, response);
    }


public void getDownExcel(List<JSONObject> jsonObjectList,String fieldList, HttpServletResponse response) throws Exception {
    //导出表名、列名
    String[] strs = fieldList.split(",");
    int cloumLength = strs.length;
    String columnNameList = "";
    String title = "每周三商机跟踪列表";
    String[] rowsName = new String[cloumLength];
    for(int k=0;k<strs.length;k++){
        String zw = strs[k].toString().substring(strs[k].toString().indexOf(";")+1);
        rowsName[k] = zw;
    }
    int dd = rowsName.length;
    List<Object[]> dataList = new ArrayList<Object[]>();
    Object[] objs = null;
    for (int i = 0; i < jsonObjectList.size(); i++) {
        JSONObject jsonObject = jsonObjectList.get(i);
        objs = new Object[rowsName.length];

        for(int j=0;j<strs.length;j++){
            String englishFields=strs[j].toString().substring(0,strs[j].toString().indexOf(";"));
            objs[j] = jsonObject.getString(englishFields);
        }
        dataList.add(objs);
    }
    ExportCustomerExcel ex = new ExportCustomerExcel(title, rowsName, dataList, response);
    ex.exportContractAccount(cloumLength);
}

    private void sendMessage(String jsonData) {
        List<JSONObject> jsonObjectList = null;
        if (!StringUtils.isBlank(jsonData)) {
            jsonObjectList = FastJsonConvert.convertJSONToArray(jsonData, JSONObject.class);
        }
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            TextMessage textMessage = new TextMessage(BaseUtils.succsessArrHourTimeRespond(jsonObjectList), true);
            try {
                myWebSocketHandler.sendMsgToAllUsers(textMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/getNameAndTel.json", method = RequestMethod.POST)
    public void getNameAndTel(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.thurTrackFacade.getNameAndTel(jsonData);
        if (null != result && result.size() > 0) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/getCurrMonthDeal.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "当月预测统计",
            notes = "当月预测统计",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getCurrMonthDeal(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getCurrMonthDeal(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

    @RequestMapping(value = "/getCurrMonthList.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "当月预测列表",
            notes = "当月预测列表",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getCurrMonthList(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getCurrMonthList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

    @RequestMapping(value = "/getAccuracyRate.json", method = RequestMethod.POST)
    @ApiOperation(
            value = "准确率统计",
            notes = "准确率统计",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getAccuracyRate(HttpServletResponse response,@RequestBody String jsonData) {
        JSONObject result = this.thurTrackFacade.getAccuracyRate(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
    }

}
